package 多线程;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author zhang lei
 * @Date 2021-11-12 16:19
 */
public class Multi2 {


    public static void main(String[] args) {

        Lock lock = new ReentrantLock();

        Condition zero = lock.newCondition();
        Condition add = lock.newCondition();
        Sell sell = new Sell(lock, zero, add);

        new Thread(sell, "小明").start();
        new Thread(sell, "老师").start();
        new Thread(sell, "黄牛").start();

        Supp supp = new Supp(lock, zero, add, sell);

        new Thread(supp, "小花").start();
        new Thread(supp, "小兰").start();
        new Thread(supp, "小马").start();
    }
}

class Sell implements Runnable{

    public Integer num = 10;
    private Lock lock;
    private Condition zero;
    private Condition add;

    public Sell(Lock lock, Condition zero, Condition add) {
        this.lock = lock;
        this.zero = zero;
        this.add = add;
    }

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                while (num == 0) {
                    zero.await();
                    add.signalAll();
                    Thread.sleep(1000);
                }
                System.out.println(Thread.currentThread().getName()+" 卖出第"+num--+"张票");
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

class Supp implements Runnable{

    private Lock lock;
    private Condition condition;
    private Condition add;
    private Sell sell;

    public Supp(Lock lock, Condition zero, Condition add, Sell sell) {
        this.lock = lock;
        this.condition = zero;
        this.add = add;
        this.sell = sell;
    }

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                while (sell.num >9) {
                    Thread.sleep(1000);
                    condition.signalAll();
                    add.await();
                }
                System.out.println(Thread.currentThread().getName()+" 添加1张票， 第"+ sell.num++ +"张票");
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
